package controllers

import (
	"github.com/revel/revel"
	"waterblabla/app/models"
	"gopkg.in/mgo.v2/bson"
)

type Manager struct {
	Controller
}

func (c Manager) GetCustomers() revel.Result {
	type Req struct {
		//models.QS `,inline`
		Sn    string `json:"sn"`
		Count int    `json:"count" valid:"Required"`
		// TODO: validate int64
		Cursor int64 `json:"cursor" valid:"Required"`
	}
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}

	var contracts []models.Contract
	if err := models.GetCustomers(req.Cursor, req.Count, &contracts); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(contracts)
}

func (c Manager) GetStatsInfo() revel.Result {
	type Req struct {
		//models.QS `,inline`
		//Count int    `json:"count" valid:"Required"`
		// TODO: validate int64
		//Cursor int64 `json:"cursor" valid:"Required"`
	}
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}

	var rst []bson.M
	if err := models.Stat(&rst); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(rst)
}

func (c Manager) Orders() revel.Result {
	type Req struct {
		models.QS `,inline`
		Count     int      `json:"count"  valid:"Required"`
		Cursor    int64    `json:"cursor" valid:"Required"`
		CursorEnd int64    `json:"cursorEnd"`
		State     int      `json:"state" valid:"Required"`
		Postman   []string `json:"postman"`
		Customer  []string `json:"customer"`
		Brands    []string `json:"brands"`
	}
	// parse
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	var orders []models.Order
	if err := models.AllOrders(req.Count, req.State, req.Postman,
	 req.Customer, req.Cursor, req.CursorEnd, &orders); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(orders)
}

func (c Manager) GetStations() revel.Result {
	type Req struct {
		models.QS `,inline`
		Count     int      `json:"count"  valid:"Required"`
		Cursor    int64    `json:"cursor" valid:"Required"`
		CursorEnd int64    `json:"cursorEnd"`
		State     int      `json:"state" valid:"Required"`
	}
	// parse
//	var req Req
//	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
//		return c.RenderResult(err)
//	}
//	var orders []models.Order
//	if err := models.AllOrders(req.Count, req.State, req.Postman,
//	 req.Customer, req.Cursor, req.CursorEnd, &orders); err != nil {
//		return c.RenderResult(err)
//	}

//	return c.RenderResult(orders)
return nil
}